package indi.zhifa.core.multidatasource.core;

import indi.zhifa.core.common.web.entity.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.transaction.Transaction;
import org.springframework.jdbc.datasource.ConnectionHolder;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class MultiDataSourceTransaction implements Transaction {

    private ZfRoutingDataSource mZfRoutingDataSource;
    private Map<String,MultiDataSourceConnectionInfo> connectionMap;

    public MultiDataSourceTransaction(DataSource pDataSource) {
        if(pDataSource instanceof ZfRoutingDataSource zfRoutingDataSource){
            mZfRoutingDataSource = zfRoutingDataSource;
            connectionMap = new ConcurrentHashMap<String,MultiDataSourceConnectionInfo>();
        }else{
            throw new ServiceException("传入的DataSource 必须是ZfRoutingDataSource");
        }
    }


    @Override
    public Connection getConnection() throws SQLException {
        String curKey = mZfRoutingDataSource.curKey();
        MultiDataSourceConnectionInfo multiDataSourceConnectionInfo = connectionMap.get(curKey);
        if(null == multiDataSourceConnectionInfo) {
            multiDataSourceConnectionInfo = new MultiDataSourceConnectionInfo();
            DataSource targetDataSource = mZfRoutingDataSource.getTargetDataSource();
            Connection connection = DataSourceUtils.getConnection(targetDataSource);
            multiDataSourceConnectionInfo.setDataSource(targetDataSource);
            multiDataSourceConnectionInfo.setConnection(connection);
            multiDataSourceConnectionInfo.setAutoCommit(connection.getAutoCommit());
            multiDataSourceConnectionInfo.setConnectionTransactional(DataSourceUtils.isConnectionTransactional(connection, targetDataSource));
            connectionMap.put(curKey, multiDataSourceConnectionInfo);
        }
        return multiDataSourceConnectionInfo.getConnection();
    }

    @Override
    public void commit() throws SQLException {
        for(MultiDataSourceConnectionInfo multiDataSourceConnectionInfo : connectionMap.values()) {
            if(!multiDataSourceConnectionInfo.isConnectionTransactional() && !multiDataSourceConnectionInfo.isAutoCommit()){
                Connection targetConnection = multiDataSourceConnectionInfo.getConnection();
                targetConnection.commit();
            }
        }
    }

    @Override
    public void rollback() throws SQLException {
        for(MultiDataSourceConnectionInfo multiDataSourceConnectionInfo : connectionMap.values()) {
            if(!multiDataSourceConnectionInfo.isConnectionTransactional() && !multiDataSourceConnectionInfo.isAutoCommit()){
                Connection targetConnection = multiDataSourceConnectionInfo.getConnection();
                targetConnection.rollback();
            }
        }
    }

    @Override
    public void close() throws SQLException {
        for(MultiDataSourceConnectionInfo multiDataSourceConnectionInfo : connectionMap.values()) {
            DataSourceUtils.releaseConnection(multiDataSourceConnectionInfo.getConnection(), multiDataSourceConnectionInfo.getDataSource());
        }
        connectionMap.clear();
    }

    @Override
    public Integer getTimeout() throws SQLException {
        var holder = (ConnectionHolder) TransactionSynchronizationManager.getResource(mZfRoutingDataSource);
        if (holder != null && holder.hasTimeout()) {
            return holder.getTimeToLiveInSeconds();
        }
        return null;
    }
}
